package com.runshu.newsmartark.fragment;

import android.view.KeyEvent;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.activity.ManagerActivity;
import com.runshu.newsmartark.adapter.MyLogsAdapter;
import com.runshu.newsmartark.base.BaseLazyFragmentPlus;
import com.runshu.newsmartark.entity.LogsManagerBean;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.mvp.contract.GetUserListContract;
import com.runshu.newsmartark.mvp.contract.LogsManagerContract;
import com.runshu.newsmartark.mvp.model.GetUserListModel;
import com.runshu.newsmartark.mvp.model.LogsManagerModel;
import com.runshu.newsmartark.mvp.presenter.GetUserListPresenter;
import com.runshu.newsmartark.mvp.presenter.LogsManagerPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.util.LodDialogClass;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.picker.DoubleTimeSelectDialog;
import com.zxl.library.DropDownMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * Demo class
 *
 * @author yu
 * @date 2020/8/27
 * @decs：
 */

public class LogsManagerFragment extends BaseLazyFragmentPlus implements LogsManagerContract.View, GetUserListContract.View , ManagerActivity.OnRefreshActivityListener {
    @BindView(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    private String headers[] = {"操作类型", "姓名", "操作时间"};
    //    0 补货 1 领取  2归还 3 全部
    private String selectTypeOne[] = {"全部", "入库", "出库"};
    private String selectTypeTwo[] = {};
    private String selectTypeThree[] = {"全部", "最近一个月", "最近二个月","最近三个月", "自定义"};
    private View contentView;
    private DoubleTimeSelectDialog mDoubleTimeSelectDialog;
    private int[] types = new int[]{DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY};
    private RecyclerView recyclerView;
    private MyLogsAdapter mAdapter;
    private List<LogsManagerBean.ListBean> mData;
    private LogsManagerPresenter managerPresenter;
    private SwipeRefreshLayout swipe_layout;
    private String operationName, operationType = "", dateType = "0", startDate, endDate;
    private int pageSize = 20;
    private int pageNum = 1;
    private boolean loading = true;
    private boolean isLoadMore = false;
    private List<UserInfoEntity> userList;
    private GetUserListPresenter userListPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.frg_logs_manager;
    }

    @Override
    protected void initView(View layoutInflateView) {
        contentView = getLayoutInflater().inflate(R.layout.content_logs_manager, null);
        swipe_layout = contentView.findViewById(R.id.swipe_layout);
        recyclerView = contentView.findViewById(R.id.recy_logs);
        managerPresenter = new LogsManagerPresenter(this, new LogsManagerModel());
        userListPresenter = new GetUserListPresenter(this, new GetUserListModel());
    }

    @Override
    protected void initData() {
        userListPresenter.getUserList();
        mData = new ArrayList<>();
        mAdapter = new MyLogsAdapter(mData);
        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(recyclerView);
        mAdapter.setEmptyView(R.layout.empty_view);

    }


    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                //退出activity前关闭菜单
                if (mDropDownMenu.isShowing()) {
                    mDropDownMenu.closeMenu();
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        });
    }


    /**
     * 设置类型和数据源：
     * DropDownMenu.KEY对应类型（DropDownMenu中的常量，参考上述核心源码）
     * DropDownMenu.VALUE对应数据源：key不是TYPE_CUSTOM则传递string[],key是TYPE_CUSTOM类型则传递对应view
     */
    private List<HashMap<String, Object>> initViewData() {
        List<HashMap<String, Object>> viewDatas = new ArrayList<>();
        HashMap<String, Object> map;
        for (int i = 0; i < headers.length; i++) {
            map = new HashMap<String, Object>();
            map.put(DropDownMenu.KEY, types[i]);
            if (i == 0) {
                map.put(DropDownMenu.VALUE, selectTypeOne);
//                map.put(DropDownMenu.SELECT_POSITION, 1);

            } else if (i == 1) {
                map.put(DropDownMenu.VALUE, selectTypeTwo);
//                map.put(DropDownMenu.SELECT_POSITION, 0);

            } else {
                map.put(DropDownMenu.VALUE, selectTypeThree);
//                map.put(DropDownMenu.SELECT_POSITION,2);

            }
            viewDatas.add(map);
        }
        return viewDatas;
    }

    @Override
    protected void bindListener() {
        //该监听回调只监听默认类型，如果是自定义view请自行设置，参照demo
        mDropDownMenu.addMenuSelectListener((index, pos, clickstr) -> {
            //index:点击的tab索引，pos：单项菜单中点击的位置索引，clickstr：点击位置的字符串
            LogUtil.e(TAG, "===index==" + index + "pos====" + pos);
            if (index == 0) {
                //   0 入库; 1 出库
//                {"全部", "入库", "出库"};
                if (pos == 0) {
                    operationType = "";
                } else if (pos == 1) {
                    operationType = "0";
                } else if (pos == 2) {
                    operationType = "1";
                } else {
                    operationType = "";

                }
            } else if (index == 1) {
                operationName = userList.get(pos).getUserCode();
            } else {
                dateType = pos + "";
            }
            //显示自定义时间  不请求接口
            if (index == 2 && pos == 3) {
                showCustomTimePicker();
            } else {
                //网络请求
                loading = false;
                isLoadMore = false;
                pageNum = 1;//设为默认加载第一页
                mData.clear();
                managerPresenter.getLogsManagerList(operationName, operationType, dateType, startDate, endDate, pageSize, pageNum);
            }

        });


        swipe_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loading = false;
                isLoadMore = false;
                pageNum = 1;//设为默认加载第一页
                mData.clear();
                managerPresenter.getLogsManagerList(operationName, operationType, dateType, startDate, endDate, pageSize, pageNum);
            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loading = false;
                isLoadMore = true;
                managerPresenter.getLogsManagerList(operationName, operationType, dateType, startDate, endDate, pageSize, pageNum);
            }
        });
        swipe_layout.setRefreshing(true);
        swipe_layout.post(() -> {
            managerPresenter.getLogsManagerList(operationName, operationType, dateType, startDate, endDate, pageSize, pageNum);
        });

    }

    private void showCustomTimePicker() {
        /**
         * 默认的周开始时间，格式如：yyyy-MM-dd
         **/
        String defaultWeekBegin = "";
        /**
         * 默认的周结束时间，格式如：yyyy-MM-dd
         */
        String defaultWeekEnd = "";

        String beginDeadTime = "1970-01-01";
        if (mDoubleTimeSelectDialog == null) {
            mDoubleTimeSelectDialog = new DoubleTimeSelectDialog(getActivity(), beginDeadTime, defaultWeekBegin, defaultWeekEnd);
            mDoubleTimeSelectDialog.setOnDateSelectFinished((startTime, endTime) -> {
                mDropDownMenu.setTabText(2, startTime + "至" + endTime);
                //请求数据
                startDate = startTime;
                endDate = endTime;
                loading = false;
                isLoadMore = false;
                pageNum = 1;//设为默认加载第一页
                mData.clear();
                managerPresenter.getLogsManagerList(operationName, operationType, dateType, startDate, endDate, pageSize, pageNum);

            });

            mDoubleTimeSelectDialog.setOnDismissListener(dialog -> {
            });
        }
        if (!mDoubleTimeSelectDialog.isShowing()) {
            mDoubleTimeSelectDialog.recoverButtonState();
            mDoubleTimeSelectDialog.show();
        }
    }

    @Override
    public void getUserListSuccess(ResponseBean responseBean) {
        userList = (List<UserInfoEntity>) responseBean.pullData();
        if (userList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (UserInfoEntity typeEntity : userList) {
            strings.add(typeEntity.getUserName());
        }
        selectTypeTwo = strings.toArray(new String[strings.size()]);
        if (mDropDownMenu!=null)
        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);
    }

    @Override
    public void OnGetLogsManagerList(ResponseBean responseBean) {
        swipe_layout.setRefreshing(false);//完成刷新
        LogsManagerBean logsManagerBean = (LogsManagerBean) responseBean.pullData();
        mData = logsManagerBean.getList();
        if (mAdapter!=null)
        if (isLoadMore) {
            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
        }
        if (mData != null && mData.size() > 0) {//有了请求数据
            if (isLoadMore) {//为true时，是加载更多获取的数据
                mAdapter.addData(mData);//加载更多的数据，add进去
            } else {
                mAdapter.setNewData(mData);//进入或者上拉加载的数据(page=1),setnewdata
            }
            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
                pageNum++;
                mAdapter.setEnableLoadMore(true);//允许加载更多
            } else {
                mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
            }

        } else {
            if (pageNum == 1) {
                //数据得清空才会显示空布局
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
            }
            mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
        }
//        mAdapter.notifyDataSetChanged();
        LodDialogClass.closeCustomCircleProgressDialog();
    }

    @Override
    public void onError(String msg) {
        LodDialogClass.closeCustomCircleProgressDialog();
        if (isLoadMore) {
            mAdapter.loadMoreFail();//请求失败的话调用loadMoreFail()
        }
        ToastUtils.showText(msg);
    }


    @Override
    public void onRefreshActivity() {
        LodDialogClass.showCustomCircleProgressDialog(context);

        if (mDropDownMenu==null){
            userListPresenter.getUserList();
        }

        loading = false;
        isLoadMore = false;
        pageNum = 1;//设为默认加载第一页
        mData.clear();
        managerPresenter.getLogsManagerList(operationName, operationType, dateType, startDate, endDate, pageSize, pageNum);
    }
}